package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.RDateUtils;
import com.rockcent.helper.SysMessageHelper;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.constants.SysMessageConstants;
import com.rockcent.mall.lib.domain.Mall;
import com.rockcent.mall.lib.domain.MallProductAudit;
import com.rockcent.mall.lib.domain.Product;
import com.rockcent.mall.lib.domain.SysMessage;
import com.rockcent.mall.lib.domain.enumclass.MallProductAuditStatus;
import com.rockcent.mall.lib.domain.enumclass.ProductStatus;
import com.rockcent.mall.lib.domain.enumclass.ProductType;
import com.rockcent.mall.lib.domain.enumclass.SysMessageType;
import com.rockcent.mall.lib.dto.MallDto;
import com.rockcent.mall.lib.dto.MallProductAuditDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.MallProductAuditRepository;
import com.rockcent.mall.lib.repository.MallProductAuditRepositoryCustom;
import com.rockcent.mall.lib.repository.MallRepository;
import com.rockcent.mall.lib.repository.MerchantProductRepository;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Date;
import java.text.MessageFormat;

/**
 * M端产品审核模块
 * Created by zhangjh on 2016/10/10.
 */
@RestController
public class MallProductAuditController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MallProductAuditController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private MallProductAuditRepository mallProductAuditRepository;

    @Autowired
    private MallRepository mallRepository;

    @Autowired
    private MerchantProductRepository merchantProductRepository;



    /**
     * @api {get} /mall/product/audit/page M端 产品审核列表
     * @apiGroup mall_product_audit
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} type <code>可选参数 允许值：ALL 全部 |GOODS 商品| SERVICE 服务</code> 类型
     * @apiParam {String} isPass <code>可选参数 允许值：YES| NO</code> 是否已审核
     * @apiParam {String} status <code>可选参数 允许值：AUDITED 通过 |UNAUDITED 未通过</code> 审核状态
     * @apiParam {String} productName  产品名称/编码
     * @apiParam {String} merchantName 商家名称
     * @apiParam {Integer} pageNo 页码
     * @apiParam {String} startAuditDate  <code>可选参数 格式:yyyy-MM-dd</code>   审核时间 范围 上限
     * @apiParam {String} endAuditDate    <code>可选参数 格式:yyyy-MM-dd</code>   审核时间 范围 下限
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     *      "data": [
     *      {
     *           "id": 1,
     *           "productName": "自提-b2测试产品",
     *           "status": "AUDITED",
     *           "merchantName": "b1测试商户 X",
     *           "type": "GOODS",
     *           "auditDate": "2016-10-10",
     *           "isPass": "NO"
     *      }
     *      ],
     *      "totalCount": 1,
     *      "totalPage": 1,
     *      "pageNo": 0,
     *      "pageSize": 10,
     *      "url": "/mall/product/audit/page",
     *      "prevUrl": "/mall/product/audit/page?pageNo=0&pageSize=10",
     *      "nextUrl": "/mall/product/audit/page?pageNo=1&pageSize=10"
     * }
     * }
     */
    @RequestMapping(value = Routes.MALL_PRODUCT_AUDIT_PAGE, method = RequestMethod.GET)
    public JsonResult searchProductAudit(MallProductAuditDto dto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            PageResult pageResult = getPage(dto.getPageNo(), dto.getPageSize());
            Boolean isPass = null;
            if (!EnumUtils.isValidEnum(Whether.class, dto.getIsPass())) {
                jsonResult.remind("isPass 数据类型必须为字符串 YES / NO",log);
                return;
            } else {
                if (Whether.valueOf(dto.getIsPass()) == Whether.YES) {
                    isPass = Boolean.TRUE;
                } else {
                    isPass = Boolean.FALSE;
                }
            }

            if (StringUtils.isNotBlank(dto.getStatus())) {
                if (!EnumUtils.isValidEnum(MallProductAuditStatus.class, dto.getStatus())) {
                    jsonResult.remind("审核状态 必须为 AUDITED(\"通过\"), UNAUDITED(\"未通过\")",log);
                    return;
                }
            }

            if (StringUtils.isNotBlank(dto.getType())) {
                if (!EnumUtils.isValidEnum(ProductType.class, dto.getType())) {
                    jsonResult.remind("类型 必须为 ALL(\"全部\"), GOODS(\"商品\"), SERVICE(\"服务\")",log);
                    return;
                }
            }

            PageResult<MallProductAuditDto> resultList = mallProductAuditRepository.listProductIsAudit(dto.getProductName(), dto.getMerchantName(), dto.getStatus(), dto.getType(), dto.getStartAuditDate(), dto.getEndAuditDate(), Whether.valueOf(dto.getIsPass()), userInfoDto.mall.getId(), pageResult);
            if (Whether.valueOf(dto.getIsPass()) == Whether.NO) {
                Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
                if (mall == null) {
                    jsonResult.remind("平台不存在,请联系开发人员",log);
                    return;
                }
                String host = mall.getCustomerClientDomain();
                if (StringUtils.isBlank(host)) {
                    host = mall.getMobileHostName();
                }

                String finalHost = host;
                resultList.data.forEach(mallProductAuditDto -> {
                    StringBuffer url = new StringBuffer();
                    //推广链接，待定
                    url.append("http://").append(finalHost)
                            .append("/wechat/goodsInfo/").append("?id=").append(mallProductAuditDto.getProductId());
                    url = url.append(mallProductAuditDto.getProductId());
                    mallProductAuditDto.setPreviewUrl(url.toString());
                });
            }
            resultList.setUrl(Routes.MALL_PRODUCT_AUDIT_PAGE);
            jsonResult.data = resultList;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/product/audit/info  M端  产品审核信息
     * @apiGroup mall_product_audit
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} id  <code>必要参数</code> 产品审核信息ID
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "id":1,
     *         "dateCreated":"2016-10-10 16:36:19",
     *         "lastUpdated":"2016-10-10 19:12:11",
     *         "version":1,
     *         "productName":"TTTT",
     *         "status":"AUDITED",
     *         "auditDate":"2016-10-10",
     *         "merchantId":2,
     *         "merchantName":"EEEEE",
     *         "type":"GOODS",
     *         "productId":7,
     *         "auditRemark":"TEST"
     *     }
     * }
     */
    @RequestMapping(value = Routes.MALL_PRODUCT_AUDIT_INFO, method = RequestMethod.GET)
    public JsonResult getProductAudit(MallProductAuditDto dto, HttpServletRequest request) {

        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind("参数错误", log);
                return;
            }
            MallProductAudit mallProductAudit = mallProductAuditRepository.findOne(dto.getId());
            jsonResult.data = mallProductAudit;
        };
        return doing.go(request, log);
    }


    /**
     * @api {put} /mall/product/audit/update  M端  产品审核
     * @apiGroup mall_product_audit
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} id  <code>必要参数</code> 产品审核信息ID
     * @apiParam {boolean} status  <code>必要参数 AUDITED | UNAUDITED</code> 是否通过
     * @apiParam {String} auditRemark <code>审核不通过时，此字段必填</code> 审核备注
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_PRODUCT_AUDIT_UPDATE, method = RequestMethod.PUT)
    public JsonResult updateProductAudit(@RequestBody MallProductAuditDto dto, HttpServletRequest request) {


        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind("参数错误 ID不能为空", log);
                return;
            }

            if (dto.getStatus() == null || !EnumUtils.isValidEnum(MallProductAuditStatus.class, dto.getStatus())) {
                jsonResult.remind("参数错误,status 必须是AUDITED(\"通过\"),UNAUDITED(\"未通过\");", log);
                return;
            }
            MallProductAudit mallProductAudit = mallProductAuditRepository.findOne(dto.getId());
            if (mallProductAudit == null) {
                jsonResult.remind("数据加载错误", log);
                return;
            }
            mallProductAudit.setIsPass(Whether.YES);

            mallProductAudit.setAuditDate(new java.util.Date());
            Product product= this.merchantProductRepository.findByIdAndMerchantId(mallProductAudit.getProductId(),mallProductAudit.getMerchantId());
            SysMessage message = null;
            String productName = product.getName();
            if (MallProductAuditStatus.AUDITED.toString().equals(dto.getStatus())) {
                mallProductAudit.setStatus(MallProductAuditStatus.AUDITED);
                mallProductAudit.setAuditRemark("通过");
                product.setStatus(ProductStatus.SELLING);
                String content = SysMessageConstants.M2B_PRODUCT_AUDIT_PASS.getContent();
                content = MessageFormat.format(content, productName);
                message = SysMessageHelper.SINGLETON.createMsgBean(SysMessageConstants.M2B_PRODUCT_AUDIT_PASS, SysMessageType.OP, content);
            }
            if (MallProductAuditStatus.UNAUDITED.toString().equals(dto.getStatus())) {
                String remark = dto.getAuditRemark();
                if (StringUtils.isBlank(remark)) {
                    jsonResult.remind("审核备注不能为空", log);
                    return;
                }
                String content = SysMessageConstants.M2B_PRODUCT_AUDIT_UNPASS.getContent();
                content = MessageFormat.format(content, productName, remark);
                mallProductAudit.setStatus(MallProductAuditStatus.UNAUDITED);
                mallProductAudit.setAuditRemark(remark);
                mallProductAudit.setIsPass(Whether.YES);
                product.setStatus(ProductStatus.AUDIT_FAIL);
                product.setAuditRemark(remark);
                message = SysMessageHelper.SINGLETON.createMsgBean(SysMessageConstants.M2B_PRODUCT_AUDIT_UNPASS, SysMessageType.OP, content);
            }
            mallProductAuditRepository.saveAndFlush(mallProductAudit);
            merchantProductRepository.saveAndFlush(product);

            //广播消息
            Long merchantId = product.getMerchantId();
            SysMessageHelper.SINGLETON.pushMsgByMallAndMerchantId(message, null, merchantId);


            jsonResult.data = mallProductAudit;

        };
        return doing.go(request, log);
    }

    /**
     *
     * @api {put} /mall/product/audit/change M端  平台产品审核状态变更
     * @apiGroup mall_product_audit
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Boolean}proAudit <code>必要参数，true|false</code>是否开启审核
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code" "1",
     * "desc" "成功",
     * }
     */
    @RequestMapping(value = Routes.MALL_PROAUDIT_CHANGE,method = RequestMethod.PUT)
    public JsonResult updateMallProAudit(HttpServletRequest request, @RequestBody MallDto dto){
        UserInfoDto userInforDto=userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Mall mall = mallRepository.findOne(userInforDto.mall.getId());
            if(mall!=null){
                mall.setProdAudit(dto.getProAudit());
                this.mallRepository.saveAndFlush(mall);
            }else{
                jsonResult.remind("加载平台信息出错",log);
                return;
            }
        };
        return  doing.go(request,log);
    }

    /**
     *
     * @api {get} /mall/product/audit/status M端  获取平台产品审核状态
     * @apiGroup mall_product_audit
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long}id <code>必要参数，不为空</code>商家认证信息ID
     * @apiSuccessExample {json} Success-Response:
     *{
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *      "id": 1,
     *      "dateCreated": "2016-05-06 17:30:29",
     *      "lastUpdated": "2016-09-25 21:10:59",
     *      "version": 31,
     *      "name": "B123aab",
     *      "hostname": "b1.b.dev.rockcent.com",
     *      "userInfoId": 2,
     *      "serveRate": "24",
     *      "shareRate": "50",
     *      "salesCode": "M@rlrSX6hR",
     *      "mobileHostName": "b1.b.dev.rockcent.com",
     *      "prodAudit": false
     *      }
     *}
     */
    @RequestMapping(value = Routes.MALL_PRODUCT_AUDIT_STATUS,method = RequestMethod.GET)
    public JsonResult getMallProAudit(HttpServletRequest request){
        UserInfoDto userInforDto=userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Mall mall = mallRepository.findOne(userInforDto.mall.getId());
            if(mall!=null){
                jsonResult.data=mall;
            }else{
                jsonResult.remind("加载平台信息出错",log);
                return;
            }
        };
        return  doing.go(request,log);
    }

}
